<?php

/**
 * 路由
 */

namespace wtfphp;

class router {
    /**
     * URL模式
     * 1：review，2：pathinfo，3：兼容
     */
    private static $_model = 1;

    //URL参数名
    private static $_varName = '_url';

    //默认模块
    private static $_dfM = 'home';

    //默认控制器
    private static $_dfC = 'index';

    //默认操作
    private static $_dfA = 'index';

    //重写规则
    private static $_rules = array();

    /**
     * 解析url
     */
    static function run() {
        //获取
        $url = '';
        if (!empty($_GET[self::$_varName])) {
            $url = $_GET[self::$_varName];
            unset($_GET[self::$_varName]);
        }
        //重写URL
        $url = self::review($url);
        //解析
        if (empty($url)) {
            $arr = array(self::$_dfM, self::$_dfC, self::$_dfA); //默认地址
        } else {
            preg_match_all('/[\w-]+/', $url, $matches);
            switch (count($matches[0])) {
                case 1:
                    $arr = array(self::$_dfM, $matches[0][0], self::$_dfA);
                    break;
                case 2:
                    $arr = array(self::$_dfM, $matches[0][0], $matches[0][1]);
                    break;
                case 3:
                    $arr = array($matches[0][0], $matches[0][1], $matches[0][2]);
                    break;
                default:
                    throw new \Exception('Url error!');
            }
        }
        //返回
        return array('module' => $arr[0], 'controller' => $arr[1], 'action' => $arr[2]);
    }

    /**
     * 添加重写规则
     */
    static function add($pattern, $replacement) {
        $pattern = str_replace('/', '\/', $pattern);
        self::$_rules[] = array($pattern, $replacement);
    }

    /**
     * 重写URL
     */
    private static function review($url) {
        foreach (self::$_rules as $v) {
            $res = preg_replace("/^{$v[0]}$/i", $v[1], $url);
            if ($url != $res) {
                //解析
                $arr = parse_url($res);
                if (!empty($arr['query'])) {
                    parse_str($arr['query'], $params);
                    $_GET = array_merge($_GET, $params);
                }
                //跳出
                $url = $arr['path'];
                break;
            }
        }

        return $url;
    }

    /**
     * 生成URL地址
     * @param $module       模块
     * @param $controller   控制器
     * @param $action       操作
     */
    static function url($module, $controller, $action) {
        //分析
        $self = '';
        if ($module == self::$_dfM) {
            if ($action == self::$_dfA) {
                if ($controller == self::$_dfC) {
                    $self = '';
                } else {
                    $self = '/' . $controller;
                }
            } else {
                $self = '/' . $controller . '/' . $action;
            }
        } else {
            $self = '/' . $module . '/' . $controller . '/' . $action;
        }
        //入口
        $url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
        //模式
        switch (self::$_model) {
            case 1:
                $url = dirname($url) . $self;
                break;
            case 2:
                $url = $url . $self;
                break;
            case 3:
                $url = $url . '?' . self::$_varName . '=' . $self;
                break;
            default:
                return null;
        }
        //返回
        return $url;
    }
}